package com.boarsoft.dao.sharding.jdbc;

import java.io.Closeable;
import java.sql.Connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.util.RandomUtil;

public class ConnectionEx implements Closeable {
	private static final Logger log = LoggerFactory.getLogger(ConnectionEx.class);

	protected Connection connection;
	protected int ref = 0;
	protected String id = RandomUtil.genUUID();

	public ConnectionEx(Connection connection) {
		this.connection = connection;
	}

	public String getId() {
		return id;
	}

	public void close(boolean force) {
		if (force) {
			if (connection == null) {
				return;
			}
			try {
				connection.close();
			} catch (Exception e) {
				log.error("Error on close connection {}", id, e);
				connection = null;
			}
		} else {
			this.close();
		}
	}

	@Override
	public void close() {
		if (ref > 1) {
			ref--;
			return;
		}
		ref = 0;
		this.close(true);
	}

	public Connection getConnection() {
		ref++;
		return connection;
	}

	public int getRef() {
		return ref;
	}
}
